package product

import (
	"encoding/json"
	"fmt"
	"gin/app/http/global"
	"gin/app/http/model/product"
	"gin/app/http/response"
	"github.com/elastic/go-elasticsearch/v8/esapi"
	"github.com/elastic/go-elasticsearch/v8/esutil"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
)

type IndexParams struct {
	CategoryId string `json:"category_id" binding:"required"`
}

type DetailParams struct {
	Id string `json:"id"`
}

func Index(c *gin.Context) {
	DecryptedData, _ := c.Get("DecryptedData")
	var params IndexParams
	if err := binding.JSON.BindBody([]byte(DecryptedData.(string)), &params); err != nil {
		response.Fail(c, "参数不正确！", gin.H{
			"error": err.Error(),
		})
		return
	}
	var arr []product.Product
	var DB = global.DB
	result := DB.Where("category_id = ?", params.CategoryId).Find(&arr)
	if result.Error != nil {
		fmt.Println("Failed to retrieve users:", result.Error)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"msg":  "请求成功!",
		"data": arr,
	})
}

func Detail(c *gin.Context) {
	DecryptedData, _ := c.Get("DecryptedData")
	var params DetailParams
	if err := binding.JSON.BindBody([]byte(DecryptedData.(string)), &params); err != nil {
		response.Fail(c, "参数不正确！", gin.H{
			"error": err.Error(),
		})
		return
	}
	var arr product.Product
	if params.Id != "" {
		var DB = global.DB
		DB.Find(&arr, params.Id)
	} else {
		arr = product.Product{}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"msg":  "请求成功!",
		"data": arr,
	})
}

type FullTextParams struct {
	Name string `json:"name"`
}

// 全文搜索
func Search(c *gin.Context) {
	DecryptedData, _ := c.Get("DecryptedData")
	var params FullTextParams
	if err := binding.JSON.BindBody([]byte(DecryptedData.(string)), &params); err != nil {
		response.Fail(c, "参数不正确！", gin.H{
			"error": err.Error(),
		})
		return
	}
	var es = global.Es

	// 构建全文搜索查询
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"name": params.Name, // 替换成您要搜索的文本
			},
		},
		"_source": true,
	}
	// 创建搜索请求
	req := esapi.SearchRequest{
		Index: []string{global.ProductIndex},
		Body:  esutil.NewJSONReader(query),
	}
	res, err := req.Do(c, es)
	if err != nil {
		response.Fail(c, "搜索失败", gin.H{"error": err})
		return
	}
	if res.IsError() {
		response.Fail(c, "搜索失败", gin.H{"error": res.String()})
		return
	}
	var searchResult map[string]interface{}

	if err := json.NewDecoder(res.Body).Decode(&searchResult); err != nil {
		response.Fail(c, "搜索结果解析失败", gin.H{"error": err})
		return
	}

	hits, ok := searchResult["hits"].(map[string]interface{})["hits"].([]interface{})
	if !ok {
		response.Fail(c, "搜索结果无效", nil)
		return
	}
	var data []interface{}
	for _, hit := range hits {
		source, ok := hit.(map[string]interface{})["_source"]
		if !ok {
			continue
		}
		data = append(data, source)
	}
	response.Success(c, "搜索成功", gin.H{"result": data})
}
